package com.zengqingfa.shardingjdbc.demo.context;

import org.apache.shardingsphere.core.yaml.config.encrypt.YamlEncryptRuleConfiguration;
import org.apache.shardingsphere.core.yaml.config.masterslave.YamlMasterSlaveRuleConfiguration;
import org.apache.shardingsphere.core.yaml.config.sharding.YamlKeyGeneratorConfiguration;
import org.apache.shardingsphere.core.yaml.config.sharding.YamlShardingRuleConfiguration;
import org.apache.shardingsphere.core.yaml.config.sharding.YamlShardingStrategyConfiguration;
import org.apache.shardingsphere.core.yaml.config.sharding.YamlTableRuleConfiguration;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @fileName: ShardingContext
 * @author: zengqf3
 * @date: 2021-6-4 21:40
 * @description:
 */
@Component
public class ShardingContext implements ApplicationContextAware {

    private Map<String, YamlTableRuleConfiguration> tables;

    private Collection<String> bindingTables;

    private Collection<String> broadcastTables;

    private String defaultDataSourceName;

    private YamlShardingStrategyConfiguration defaultDatabaseStrategy;

    private YamlShardingStrategyConfiguration defaultTableStrategy;

    private YamlKeyGeneratorConfiguration defaultKeyGenerator;

    private Map<String, YamlMasterSlaveRuleConfiguration> masterSlaveRules;

    private YamlEncryptRuleConfiguration encryptRule;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        YamlShardingRuleConfiguration config = applicationContext.getBean(YamlShardingRuleConfiguration.class);
        tables = config.getTables();
        bindingTables = config.getBindingTables();
        broadcastTables = config.getBroadcastTables();
        defaultDataSourceName = config.getDefaultDataSourceName();
        defaultDatabaseStrategy = config.getDefaultDatabaseStrategy();
        defaultTableStrategy = config.getDefaultTableStrategy();
        defaultKeyGenerator = config.getDefaultKeyGenerator();
        masterSlaveRules = config.getMasterSlaveRules();
        encryptRule = config.getEncryptRule();
    }
}
